package org.ligson.fwc.core.id.impl;

import org.ligson.fwc.core.dao.BaseDao;
import org.ligson.fwc.core.entity.BasicEntity;
import org.ligson.fwc.core.entity.Pagination;
import org.ligson.fwc.core.id.IdGenerator;
import org.apache.commons.collections.CollectionUtils;

import java.lang.reflect.Method;
import java.math.BigInteger;

/**
 * Created by ligson on 2017/8/8.
 */
public class IdentityGenerator implements IdGenerator<BigInteger> {
    private Class<? extends BasicEntity> entityClass;

    @Override
    public BigInteger generatorId(BaseDao baseDao) {
        Class modelClazz = baseDao.getEntityClass();
        try {
            Object object = modelClazz.newInstance();
            BasicEntity basicEntity = (BasicEntity) object;
            String pkName = basicEntity.primaryKey();
            basicEntity.setSort(pkName);
            basicEntity.setOrder("desc");
            basicEntity.setPageNum(1);
            basicEntity.setMax(10);
            Pagination<BasicEntity> page = baseDao.getPaginationList(basicEntity);
            if (CollectionUtils.isNotEmpty(page.getDatas())) {
                BasicEntity entity = page.getDatas().get(0);
                Method method = modelClazz.getDeclaredMethod("get" + Character.toUpperCase(pkName.charAt(0)) + pkName.substring(1));
                BigInteger bigInteger = (BigInteger) method.invoke(entity);
                return bigInteger.add(BigInteger.ONE);
            }
            //modelClazz.getDeclaredMethod("")
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
